package control

import (
	"bytes"
	"crypto/md5"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/disintegration/imaging"
	"github.com/golang-jwt/jwt/v4"
	"github.com/labstack/echo/v4"
	log "github.com/sirupsen/logrus"
	"github.com/zxysilent/utils"
	"io"
	"io/ioutil"
	"os"
	"strings"
	"turingApi/conf"
	"turingApi/model"
)

var (
	openid string
	ret    = echo.Map{"status": "failed"}
)

func UploadToAliOss(file string) (string, error) {
	var baseUrl = "https://s.pnpai.com/"
	client, err := oss.New(
		os.Getenv("ALI_ENDPOINT"),
		os.Getenv("ALI_ACCESS_KEY"),
		os.Getenv("ALI_ACCESS_KEY_SECRET"))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	bucket, err := client.Bucket(os.Getenv("ALI_BUCKET_NAME"))
	if err != nil {
		conf.Logger.Error(fmt.Sprintf("Error: %s", err))
		return "", err
	}
	log.Println(bucket.GetConfig().Endpoint)

	fd, err := os.Open(file)
	if err != nil {
		conf.Logger.Error(fmt.Sprintf("Error: %s", err))
		return "", err
	}
	defer fd.Close()

	target := fmt.Sprintf("%s/%x.%s", os.Getenv("ALI_OSS_PATH"), md5.Sum([]byte(file)), strings.Split(file, ".")[1])
	conf.Logger.Info(fmt.Sprintf("待上传的文件：%s", target))

	err = bucket.PutObject(target, fd)
	if err != nil {
		conf.Logger.Error(fmt.Sprintf("Error: %s", err))
		return "", err
	}
	return baseUrl + target, err
}

func UploadHandler(c echo.Context) error {

	if c.Get("user") != nil {
		user := c.Get("user").(*jwt.Token)
		claims := user.Claims.(*JwtCustomClaims)
		openid = claims.OpenId
	}
	u, has := model.UserGetByOpenid(openid)
	if has {
		file, err := c.FormFile("file")
		if err != nil {
			return err
		}
		src, err := file.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		localFileName := fmt.Sprintf("static/upload/thumb_%s", file.Filename)
		dst, err := os.Create(localFileName)
		if err != nil {
			return err
		}
		defer dst.Close()

		// Copy
		if _, err = io.Copy(dst, src); err != nil {
			return err
		}

		imgData, _ := ioutil.ReadFile(localFileName)
		buf := bytes.NewBuffer(imgData)
		image, err := imaging.Decode(buf)
		if err != nil {
			conf.Logger.Error(fmt.Sprintf("Error decoding"))
			return err
		}

		image = imaging.Resize(image, 500, 0, imaging.Lanczos)
		err = imaging.Save(image, localFileName)
		if err != nil {
			conf.Logger.Error(fmt.Sprintf("Error saving image"))
			return err
		}
		ossUrl, err := UploadToAliOss(localFileName)
		if err != nil {
			conf.Logger.Error(fmt.Sprintf("Error while uploading image to oss: %v", err))
			return err
		}
		//
		u.Avatar = ossUrl
		if err := model.UserEdit(u); err != nil {
			conf.Logger.Error(fmt.Sprintf("Error edit user: %v", err))
			return err
		}
		return c.JSON(utils.Succ("succ", u))
	}
	return c.JSON(utils.Fail("文件上传失败"))

}
